import React from 'react';
import { asyncComponent } from 'react-async-component';
import { Route, withRouter, Switch, Redirect, } from 'react-router-dom';
import {inject, observer} from 'mobx-react';
import { TabPage, routeBackToUpperlevel } from 'weaver-mobile-page';
import {Tools, Icon} from 'weaver-mobile';
import Create from '../create/index';
const getLabel = Tools.getLabel;
const coms = {
  index: asyncComponent({
    resolve: () => import("../base/index")
  }),
  discussData: asyncComponent({
    resolve: () => import("../base/discussData")
  }),

}

@routeBackToUpperlevel
@inject('viewWorkplanStore')
@inject('createStore')
@withRouter
@observer
class Detail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nowTab:0
    };
  }
  componentWillMount() {
    let pathstr = window.location.hash && window.location.hash.split('#');
    const { initWorkPlan,setParams } = this.props.viewWorkplanStore;
    initWorkPlan();
    // const workplanId = this.props.location.search ? this.props.location.search.split('=')[1]:(this.props.location&&this.props.location.query&&this.props.location.query.workplanId)
    // localStorage.setItem('workid',workplanId);
    const URL = this.props.location.search ? this.props.location.search.split('?')[1] : ''
    const url = URL.length > 0 ? URL.split('&') : [];
    const Arr = this.getQuery(url);
    if(Arr['fromType']){
      setParams({fromType:Arr['fromType']})
    }else{
      setParams({fromType:''})
    }
    let isfromMessageCenter = this.props.location.search ? Arr['isfromMessageCenter'] : this.props.location&&this.props.location.query&&this.props.location.query.isfromMessageCenter;
    setParams({isfromMessageCenter:isfromMessageCenter, isSingelViewWorkplan: false})
    this.setPage(pathstr[1])
  }

  getQuery = (search)=>{
    let params ={}
    search.map((v,index)=>{
      const tempV = v.split('=');
      params[tempV[0]] = tempV[1];
      return '';
    });
    return params
  }

  componentDidMount() {
    let { changeWorkplanID, setParams} = this.props.viewWorkplanStore;
    if(localStorage) {
      localStorage.workid && changeWorkplanID(localStorage.workid);
    }
    // getPreview();
    // 获得相关交流附加信息
    // initReplyAttachList();
    // this.props.history.push('/calendar/detail/index')
  }

  componentWillUnmount() {
    localStorage.removeItem('workid');
    window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: '' })
  }



  componentWillReceiveProps (nextProps) {
    // const prePath = this.props.location.pathname;
    // const curPath = nextProps.location.pathname;
    // if (curPath && curPath !== prePath) {
    //   this.setPage(curPath);
    // }
  }

  setPage = (path) => {
    if (path.indexOf('detail/index') > -1) { this.setState({ nowTab: 0 }); }
    if (path.indexOf('detail/discussData') > -1) {this.setState({ nowTab: 1 }); }
  }
   // 点击tab页切换
   changeTab = (tab,index) => {
    let pathstr = window.location.hash && window.location.hash.split('#')[1].split('/detail');
    switch(tab.key) {
      case 1: this.setPath(index, `${pathstr[0]}/detail/index`); this.setState({nowTab: 0}); break;
      case 2: this.setPath(index, `${pathstr[0]}/detail/discussData`);this.setState({nowTab: 1}); break;
      default: ;
    }
  }

  setPath = (key, path) => {
    this.props.history.push(path);
  }

  render() {
    const { workplanid, noRight, noSecretRight, noData } = this.props.viewWorkplanStore;
    const { isEdit } = this.props.createStore
    let tabs = [];
    if(noRight || noSecretRight || noData) {
      tabs = [];
    }else{
      if(workplanid && workplanid.indexOf('R') < 0 && !isEdit) {
        tabs.push(
          { title: getLabel(387394,'详细信息'),key:1 },
          { title: getLabel(15153,'相关交流'),key:2 }
        )
      }else if(isEdit){
        tabs.push({ title: getLabel(387394,'详细信息'),key:1 })
      }else{
        tabs.push({ title: getLabel(387394,'详细信息'),key:1 })
      }
    }
    // console.log(tabs)
    const tabProps = {
      onChange: (tab,index) => { this.changeTab(tab,index) },
      page: this.state.nowTab
    };
    // let H = window.screen.height;
    return (
      <div>
        {noRight?<div className='no-right'>
          <div className='icon-noright'>
            <Icon type='wuquanxian' size='lg'/>
          </div>
          <div className='message'>
            {getLabel(2012,'对不起，您暂时没有权限！')}
          </div>
        </div>:noData?<div className='no-right'>
          <div className='icon-noright'>
            <Icon type='wuquanxian' size='lg'/>
          </div>
          <div className='message'>
            {getLabel(508094,'该日程已被删除！')}
          </div>
        </div>:noSecretRight?<div className='no-right'>
          <div className='icon-noright'>
            <Icon type='wuquanxian' size='lg'/>
          </div>
          <div className='message'>
            {getLabel(501082 ,'对不起，您的人员密级不足以查看该内容')}
          </div>
        </div>:<TabPage
          tabs={tabs}
          tabProps={tabProps}
          className="preview-workplan-tabs"
        />
    }
          {!noRight&&!noData&&!noSecretRight&&<div className='detail-content workplan-detail-container' style={{}}>
            <Switch>
              <Route
                key="index"
                path="**/detail/index"
                component={coms.index}
              />
              <Route
                key="discussData"
                path="**/detail/discussData"
                component={coms.discussData}
              />
              <Route
                key="edit"
                path={'**/detail/create'}
                render={()=>(
                  <div id="edit" style={{height: '100%'}}>
                    <Create />
                  </div>
                )}
              />
              <Redirect exact path="**/detail" to={{pathname: '**/detail/index'}} />
            </Switch>
          </div>
          }
      </div>
    );
  }
}

export default Detail;